import axios from 'axios'

// 获取环境变量中的后端URL，如果不存在则使用默认值
const backendHost = import.meta.env.VITE_BACKEND_HOST || 'localhost'
const backendPort = import.meta.env.VITE_BACKEND_PORT || '8000'
const baseURL = `http://${backendHost}:${backendPort}`

const api = axios.create({
  baseURL,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
      // 确保 Content-Type 设置正确
      if (!config.headers['Content-Type']) {
        config.headers['Content-Type'] = 'application/json'
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401 || error.response?.status === 403) {
      // 只在非登录请求时重定向
      if (!error.config.url?.includes('/auth/login')) {
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        if (window.location.pathname !== '/login') {
          window.location.href = '/login'
        }
      }
    }
    return Promise.reject(error)
  }
)

const auth = {
  login: (username: string, password: string) =>
    api.post('/api/v1/auth/login', new URLSearchParams({
      username,
      password,
    }), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    }),
  register: (username: string, email: string, password: string, fullName: string) =>
    api.post('/api/v1/auth/register', {
      username,
      email,
      password,
      full_name: fullName,
      is_active: true,
      is_superuser: false,
    }),
}

const users = {
  list: () => api.get('/api/v1/users'),
  get: (id: number) => api.get(`/api/v1/users/${id}`),
  getMe: () => api.get('/api/v1/users/me'),
  create: (userData: any) => api.post('/api/v1/users', userData),
  update: (id: number, userData: any) => api.put(`/api/v1/users/${id}`, userData),
  delete: (id: number) => api.delete(`/api/v1/users/${id}`),
  forSharing: () => api.get('/api/users/for-sharing'),
}

const workflows = {
  list: () => api.get('/api/workflows'),
  get: (id: number) => api.get(`/api/workflows/${id}`),
  create: (workflowData: any) => api.post('/api/workflows', workflowData),
  update: (id: number, workflowData: any) => api.put(`/api/workflows/${id}`, workflowData),
  delete: (id: number) => api.delete(`/api/workflows/${id}`),
  execute: (id: number) => api.post(`/api/workflows/${id}/execute`),
  copy: (id: number, copyData: any) => api.post(`/api/workflows/${id}/copy`, copyData),
  share: (id: number, shareData: any) => api.post(`/api/workflows/${id}/share`, shareData),
  getShares: (id: number) => api.get(`/api/workflows/${id}/shares`),
}

export { auth, users, workflows }
export default api 